/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bimager.jtwain;


import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.jar.JarInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Amskape
 */
public class jtwain {
     
    
    
        protected native String[] getSourceList();
        protected native String[]   aqcuireImage(String productName,String filename,String folder);
      //  protected native void  rotateRight(String path,String filename);
      //  protected native void  rotateLeft(String path,String filename);
      //  protected native void  FlipVertical(String path,String filename);
     // //  protected native void  FlipHorizontal(String path,String filename);
       // protected native int[]  getPixels(String path,String filename);
        //protected native int[]  getRightRotatedPixels(int[] pixels,int width,int height);
       // protected native int[]  getLeftRotatedPixels(int[]pixels);
        protected native void  saveTiff(String path,String filename,int width,int height,int[]pixels,int samples,int samplesperpixels);  
          
          
        static Path tempDir=null;
        static String dllJarFolder = "win32";
        static String[] DLLresources = {"TWAIN_32.dll","glut32.dll","jpeg62.dll","zlib1.dll","libtiff3.dll","jtwain.dll"};
        static private void extract(File fn, URL url)throws IOException{
                        InputStream      in  = url.openStream();
                        FileOutputStream out = new FileOutputStream(fn);
                        byte[] buffer=new byte[4096];
                        int count=0;
                        while((count=in.read(buffer))>0){
                        out.write(buffer,0,count);
                           }
                        
                         out.close();
                        in.close();
  }
          
        
        
        static {
        
         /* for (String dll : DLLresources) {
          * urls[j] = jtwain.class.getResource(dllJarFolder+"/"+dll);
          * }*/
            
           
          // URL TWAIN_32dll = jtwain.class.getResource("win32/TWAIN_32.dll");
          // URL jtwaindll = jtwain.class.getResource("win32/jtwain.dll");
          // URL glut32 = jtwain.class.getResource("win32/glut32.dll");
          // URL jpeg62 = jtwain.class.getResource("win32/jpeg62.dll");
          // URL libimage = jtwain.class.getResource("win32/libimage.dll");
           //URL libpng13 = jtwain.class.getResource("win32/libpng13.dll");
         //  URL zlib1 = jtwain.class.getResource("win32/zlib1.dll");
         //  URL libtiff3 = jtwain.class.getResource("win32/libtiff3.dll");
            try {
                  //Path tempPath = Paths.get(System.getProperty("user.home"), "amskape007");
                
         
                 File TempDir = new  File(System.getProperty("java.io.tmpdir"));
                  
                  File[] listofpreviousDir;
                  listofpreviousDir = TempDir.listFiles(new FilenameFilter() {
                  
                  @Override
                  public boolean accept(File dir, String name) {
                  
                  if(name.startsWith("bimagertwain"))
                  {
                  
                  return true;
                  
                  }
                  return false;
                  }
                  });
                  
                  for (File f : listofpreviousDir) {
                  
                  if(f.isDirectory())
                  {
                  
                  File[] temp;
                  
                  temp = f.listFiles();
                  for(int i=0;i<temp.length;i++)
                  {
                  
                  // Delete each file in the folder
                  temp[i].delete();
                 
                 }
                  f.delete();
                  }
                  }
                   File baseDir = new File(System.getProperty("java.io.tmpdir"));
                   String tempfoldername= "bimagertwain";
                  
                   File dir = new File(baseDir,tempfoldername.concat( Long.toString(System.nanoTime())) );
                   dir.mkdir();
                   //Path tempPath = Files.createTempDirectory("bimagertwain");
                   //File   dir    = tempdir;//tempPath.toFile();//new File(System.getProperty("java.io.tmpdir"),"amskapetwain");
                 
                   
                     for (String dll : DLLresources) {
                          File dllfile = new File(dir, dll);
                          dllfile.deleteOnExit();
                          URL dllURL =  jtwain.class.getResource(dllJarFolder+"/"+dll);
                          if(!dllfile.exists())
                               extract(dllfile, dllURL);
                          
                          
                          
                          System.load(dllfile.getAbsolutePath());
                     }
                   
                   
            } catch (IOException ex) {
                Logger.getLogger(jtwain.class.getName()).log(Level.SEVERE, null, ex);
            }
          
            
           
        
        }
        public void finalize() {
            
        System.out.println("jtwain garbage collected");
    }
       public static void main(String[] args) {
       
                //  int a[] = {255,202,100};
                  //char a2[] = new char[3];
                    
             String filename = "ScannedImage_"+new Date().getTime()+".tif";
             File imageFolder = new File(filename);
             String name = imageFolder.getAbsolutePath();
             int i = imageFolder.getAbsolutePath().lastIndexOf(System.getProperty("file.separator"));
            System.out.println(name.subSequence(0, i));
               // System.out.println();
            
     jtwain jt = new jtwain();
       // File f = new File("E:\\Workspace\\Netbeans\\AmskapeTwain\\src\\com\\amskape\\jtwain\\win32","binesh.tif");
        //System.out.println(f.getAbsolutePath());
       //jt.rotateRight("", f.getAbsolutePath());
       // jt.FlipHorizontal("", f.getAbsolutePath());
       // th.rotateRight(f.getAbsolutePath());
      
		//jbt.initTwain();
		
       // jbt.initTwain();
	   
	
        // TODO code application logic here
    }
}
